package com.flow.service.facade.check.user.service.impl;

import com.flow.framework.cache.constant.FrameworkCacheConstant;
import com.flow.framework.cache.manager.PojoCacheManager;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.type.TypeReference;
import com.flow.service.facade.check.CheckErrorCode;
import com.flow.service.facade.check.CheckModuleConstant;
import com.flow.service.facade.check.user.module.service.IUserModuleService;
import com.flow.service.facade.check.user.pojo.vo.UserModuleVo;
import com.flow.service.facade.check.user.service.IUserModuleCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用户模块缓存服务
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2023/4/9
 */
@Service
@Slf4j
@RequiredArgsConstructor
@RefreshScope
public class UserModuleCacheServiceImpl implements IUserModuleCacheService {

    private static final int CACHE_TIME = 60 * 60 * 1000;

    private static final PojoCacheManager POJO_CACHE_MANAGER = PojoCacheManager.getByPlaceholder(CheckModuleConstant.APPLICATION_NAME_EXPRESSION);

    private final IUserModuleService userModuleService;

    /**
     * 根据id获取用户
     *
     * @param userId    userId
     * @param allowNull allowNull
     * @return
     */
    @Override
    @SuppressWarnings("deprecation")
    public UserModuleVo getById(String userId, boolean allowNull) {
        UserModuleVo userModuleVo = POJO_CACHE_MANAGER.bigGet(0, UserModuleVo.class.getName()
                        + FrameworkCacheConstant.CACHE_KEY_SPLIT_STRING + FrameworkCacheConstant.CACHE_VALUE_ID_KEY + userId,
                new TypeReference<UserModuleVo>() {
                }, CACHE_TIME, TimeUnit.MILLISECONDS, () -> userModuleService.getById(userId, true));
        if (!allowNull && null == userModuleVo) {
            log.error("can't find user. id : {}", userId);
            throw new CheckedException(CheckErrorCode.USER_NOT_EXIST_ERROR);
        }
        return userModuleVo;
    }
}